<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data: { type: Object as () => any, required: true },
    title: { type: String, required: true },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref({
    title: {
      text: props.title,
      left: 'center',
      top: '8%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'item',
      appendToBody: true, // 关键设置，挂载到<body>下，避免被选项卡遮挡
      position: function (point: any, params: any, dom: any, rect: any, size: any) {
        return [point[0] + 10, point[1] + 30]; // 将提示框向右偏移10像素
      },
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 400;
        },
        animationEasing: 'exponentialInOut',
        animationType: 'scale',
        center: ['50%', '58%'],
        color: ['#5ab1ef', '#8e7cc3', '#b6a2de', '#67e0e3', '#2ec7c9'],
        data: [{ name: '', value: 0 }].sort((a, b) => {
          return a.value - b.value;
        }),
        name: props.title,
        radius: '70%',
        // roseType: 'radius',
        type: 'pie',
        label: {
          // 添加标签配置
          show: true,
          position: 'inside', // 内部标签（参考原图）
          formatter: '{b}\n{c}',
          color: '#fff', // 白色文本
          fontWeight: 'bold',
          fontSize: 12,
          textShadowBlur: 10,
          textShadowColor: 'rgba(0, 0, 0, 0.5)',
        },
        itemStyle: {
          borderWidth: 2, // 添加白色描边
          borderColor: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            textBorderColor: '#000',
            textBorderWidth: 2,
          },
        },
      },
    ],
  });

  const initCharts = () => {
    try {
      option.value.series[0].data = props.data ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.value.series[0].data = props.data ?? [];
    if (chartRef.value && chartInstance) {
      chartInstance.setOption(option.value, true);
    }
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => props.data,
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
